﻿using System;
using System.Linq;

namespace N2.BlogEngine
{
	using Items;
	using be = global::BlogEngine.Core;

	static partial class ItemExtensions
	{
		public static be.Category AsBlogEngine(this BeCategory category)
		{
			return new be.Category(
				category.Title,
				category.GetDetail<string>("Description", string.Empty)) {
				Id = category.ID.ToGuid(),
			};
		}

		public static be.Comment AsBlogEngine(this BeComment comment, be.Post bePost)
		{
			Uri _website;
			
			return new be.Comment {
				Id = comment.ID.ToGuid(),
				IsApproved = comment.Published.HasValue && comment.Published.Value <= DateTime.Now,
				Author = comment.SavedBy,
				Website = Uri.TryCreate(
						comment.GetDetail<string>("Website", string.Empty),
						UriKind.Absolute,
						out _website)
					? _website
					: default(Uri),
				Email = comment.GetDetail<string>("Email", string.Empty),
				Content = comment.GetDetail<string>("Content", string.Empty),
				DateCreated = comment.Created,
				Parent = bePost ?? (comment.Parent as BePost).AsBlogEngine(),
				Country = comment.GetDetail<string>("Country", string.Empty),
				IP = comment.GetDetail<string>("IP", string.Empty),
			};
		}

		public static be.Post AsBlogEngine(this BePost post)
		{
			return new be.Post {
				Id = post.ID.ToGuid(),
				Title = post.Title,
				Content = post.GetDetail<string>("Content", null),
				Description = post.GetDetail<string>("Description", null),
				DateCreated = post.Created,
				DateModified = post.Updated,
				Author = post.SavedBy,
				IsPublished = post.Published.HasValue,
				IsCommentsEnabled = post.GetDetail<bool>("IsCommentsEnabled", false),
				Raters = post.GetDetail<int>("Raters", 0),
				Rating = (float)post.GetDetail<double>("Rating", 0.0),
				Slug = post.GetDetail<string>("Slug", string.Empty),
			};
		}

		public static be.Page AsBlogEngine(this BePage page)
		{
			return new be.Page {
				Id = page.ID.ToGuid(),
				Title = page.Title,
				Content = page.GetDetail<string>("Content", string.Empty),
				Description = page.GetDetail<string>("Description", string.Empty),
				DateCreated = page.Created,
				DateModified = page.Updated,
				Keywords = page.GetDetail<string>("Keywords", string.Empty),
				IsPublished = page.Published.HasValue && page.Published.Value <= DateTime.Now,
				IsFrontPage = page.GetDetail<bool>("IsFrontPage", false),
				Parent = page.Parent.ID.ToGuid(),
				ShowInList = page.Visible,
			};
		}
	}
}
